package org.jz.gae.redbook.spb.client.slate.location;

import java.math.BigDecimal;

import org.jz.gae.redbook.spb.client.toolkit.Slate;
import org.jz.gae.redbook.spb.shared.LocationEntityView;
import org.jz.gae.redbook.spb.shared.MapHelper;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.maps.client.MapType;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.control.LargeMapControl;
import com.google.gwt.maps.client.event.MarkerDragEndHandler;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.maps.client.overlay.MarkerOptions;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class LocationAppendPlate extends Composite
{
      private VerticalPanel rootPanel = new VerticalPanel();
	  private final Button saveButton = new Button("Сохранить");
	  private final Button cancelButton = new Button("Отмена");;
	  private LocationPropertiesPanel locationPropertiesPanel = new LocationPropertiesPanel();
	private Slate slate;
	private ClickHandler submitEvent; 
	  private MapWidget mapPanel;


	public LocationAppendPlate() 
	{
		SimplePanel contentTableDecorator = new SimplePanel();
	  initWidget(contentTableDecorator);
	  contentTableDecorator.setWidth("100%");
	  initilizeInterface();
      contentTableDecorator.add(rootPanel);
      
      saveButton.addClickHandler(new ClickHandler(){
    	  @Override
    	  public void onClick(ClickEvent event)
          {
              submitOperation();
    	  }
      });
      cancelButton.addClickHandler(new ClickHandler(){
    	  @Override
    	  public void onClick(ClickEvent event)
          {
              cancelOperation();
    	  }
      });
	}

	private void initilizeInterface()
	{
		rootPanel.setWidth("100%");
		locationPropertiesPanel.setWidth("100%");
		rootPanel.add(locationPropertiesPanel);
	    HorizontalPanel menuPanel = new HorizontalPanel();
	    menuPanel.add(saveButton);
	    menuPanel.add(cancelButton);
	    rootPanel.add(menuPanel);
	    /**/
	    LatLng mapCenter = LatLng.newInstance(MapHelper.MAP_CENTER_LAT, MapHelper.MAP_CENTER_LONG);
	    int mapZoomLevel = MapHelper.MAP_ZOOM_LEVEL;
	    mapPanel = new MapWidget(mapCenter, mapZoomLevel);
	    mapPanel.setCenter(mapCenter, mapZoomLevel, MapType.getNormalMap());
		mapPanel.setWidth("100%");
		mapPanel.setHeight("50em");
		mapPanel.addControl(new LargeMapControl());
	    rootPanel.add(mapPanel);
	}

	public void appendEntityView(
			Slate _Slate,
			ClickHandler _SubmitEvent)
	{
		slate = _Slate;
		submitEvent = _SubmitEvent;
		locationPropertiesPanel.setSlate(slate);
		LocationEntityView newLocation = new LocationEntityView();
		newLocation.setLocationWorkName("Новое местонахождение");
		newLocation.setLocationCoordLat(new BigDecimal(MapHelper.MAP_CENTER_LAT));
		newLocation.setLocationCoordLong(new BigDecimal(MapHelper.MAP_CENTER_LONG));
		newLocation.setLocationCoordLatitude(MapHelper.MAP_CENTER_LAT);
		newLocation.setLocationCoordLongitude(MapHelper.MAP_CENTER_LONG);
		initializeNewEntityView(newLocation);
		locationPropertiesPanel.displayInformation(newLocation);
		slate.exposePlate(this);
		LatLng locationPont = LatLng.newInstance(newLocation.getLocationCoordLatitude(), newLocation.getLocationCoordLongitude());
		MarkerOptions locationOptions =  MarkerOptions.newInstance();
		locationOptions.setDraggable(true);
		final Marker locationMarker = new Marker(locationPont, locationOptions);
		locationMarker.addMarkerDragEndHandler(new MarkerDragEndHandler()
		{
			@Override
			public void onDragEnd(MarkerDragEndEvent event)
			{
				locationPropertiesPanel.setLocationCoords(event.getSender().getLatLng());
			}
		});
		locationPropertiesPanel.setLocationCoordChangeListener(new LocationPropertiesPanel.LocationCoordChangeListener()
		{
			@Override
			public void locationCoordsChanged(
					double _Latitude, 
					double _Longitude)
			{
				locationMarker.setLatLng(LatLng.newInstance(_Latitude, _Longitude));
	        }
		});
		mapPanel.addOverlay(locationMarker);
	}
	
	protected void initializeNewEntityView(
			LocationEntityView _NewEntityView)
	{
	    /* Can be override */	
	}
	
	private void cancelOperation()
	{
		slate.closeTopPlate();
	}
	
	private void submitOperation()
	{
		try
		{
			LocationEntityView locationEntityView = locationPropertiesPanel.pickUpInformation();
			if (
					(locationEntityView.getLocationDistrictKey() == null)
		            ||
					(locationEntityView.getLocationDistrictKey().equals(""))
			   )
			{
				throw new Exception("Необходимо выбрать район");
			}
			if (
					(locationEntityView.getLocationSpeciesKey() == null)
		            ||
					(locationEntityView.getLocationSpeciesKey().equals(""))
			   )
			{
				throw new Exception("Необходимо выбрать вид");
			}
		    slate.getContainerAgent().getRpcService().addLocation(locationEntityView, new AsyncCallback<LocationEntityView>() {
		        public void onSuccess(LocationEntityView result) 
		        {
		            slate.closeTopPlate();
		            submitEvent.onClick(new ClickEvent(){});
		        }
		        public void onFailure(Throwable caught) 
		        {
		             Window.alert("Error appending location");
		        }
		    });
			
		}
		catch(Exception ex)
		{
            Window.alert("Invalid data : " + ex.getMessage());
		}
		
	}
}